package com.zch.house.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zch.house.dao.RoleDao;
import com.zch.house.entity.Role;
import com.zch.house.service.RoleService;
import com.zch.house.util.XmlSession;

public class RoleServiceImpl extends XmlSession implements RoleService {
	private final int PAGE_SIZE = 20;

	@Override
	public List<Role> getAllRoleByPage(String name, int pageIndex) {
		// 使用map集合来存放参数
		Map<String, Object> map = new HashMap<>();
		map.put("name", name);
		int firstRow = (pageIndex - 1) * PAGE_SIZE + 1;
		int lastRow = pageIndex * PAGE_SIZE;
		map.put("firstRow", firstRow);
		map.put("lastRow", lastRow);
		
		//加载配置文件
		initSession();
		//获得mapper的代理类
		RoleDao dao = session.getMapper(RoleDao.class);
		//调用dao层方法
		List<Role> list = dao.getAllRole(map);
		//提交事务并关闭session
		closeSession();
		return list;
	}

	@Override
	public int getTotalCount(String name) {
		// 使用map集合来存放参数
		Map<String, Object> map = new HashMap<>();
		map.put("name", name);
		
		//加载配置文件
		initSession();
		//获得mapper的代理类
		RoleDao dao = session.getMapper(RoleDao.class);
		// 调用dao层方法获得查询到的所有数据的个数
		int counts = dao.getTotalCount(map);
		//提交事务并关闭session
		closeSession();
		// 计算总页数
		int totalPages = counts % PAGE_SIZE == 0 ? counts / PAGE_SIZE : counts / PAGE_SIZE + 1;
		return totalPages;
	}

	@Override
	public Role getRoleById(int id) {
		//加载配置文件
		initSession();
		//获得mapper的代理类
		RoleDao dao = session.getMapper(RoleDao.class);
		//调用dao层方法
		Role role = dao.getRoleById(id);
		//提交事务并关闭session
		closeSession();
		return role;
	}

	@Override
	public boolean addRole(Role role) {
		//加载配置文件
		initSession();
		//获得mapper的代理类
		RoleDao dao = session.getMapper(RoleDao.class);
		//调用dao层方法
		boolean flag = dao.addRole(role);
		//提交事务并关闭session
		closeSession();
		return flag;
	}

	@Override
	public boolean deleteRole(int id) {
		//加载配置文件
		initSession();
		//获得mapper的代理类
		RoleDao dao = session.getMapper(RoleDao.class);
		//调用dao层方法
		boolean flag = dao.deleteRole(id);
		//提交事务并关闭session
		closeSession();
		return flag;
	}

	@Override
	public boolean updateRole(Role role) {
		//加载配置文件
		initSession();
		//获得mapper的代理类
		RoleDao dao = session.getMapper(RoleDao.class);
		//调用dao层方法
		boolean flag = dao.updateRole(role);
		//提交事务并关闭session
		closeSession();
		return flag;
	}

}
